package features;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import javax.swing.JFileChooser;
import javax.swing.JTextPane;

import notepad.Notepad;

public class File extends Feature{
	
	public File(JTextPane textPane){
		this.textPane = textPane;
	}
	
	public void open(Notepad n) {
		int returnVal = jfc.showOpenDialog(n); // to show JFileChooser
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			// to erase any text in the text area before adding new text
			n.textPane.setText(null);
			try {
				// to get the name of the selected file
				fileName = jfc.getSelectedFile().getPath();
				// to read the selected file
				Reader in = new FileReader(jfc.getSelectedFile());
				StringBuilder sb = new StringBuilder();
				// 100000 is the max. char can be written in the text area
				char[] buff = new char[100000];
				int nch;
				while ((nch = in.read(buff, 0, buff.length)) != -1) {
					sb.append(buff, 0, nch);
				}
				text = sb.toString();
				n.textPane.setText(text);
			} catch (FileNotFoundException x) {
				// no action
			} catch (IOException ioe) {
				System.err.println("I/O Error on Open");
			}
		}
		n.setTitle(jfc.getSelectedFile().getName() + " - JAVA Notepad");
	}
	
	public void newFile(Notepad n) {
		n.textPane.setText("");
		fileName = null;
		n.setTitle("Untitled - JAVA Notepad SPL1");
	}
}
